package com.zhou.springsecurityoauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author zhou
 * @version 1.0
 * @date 2022/10/8 - 10 - 08 - 11:33
 * @description com.zhou.springsecurityoauth2.config
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean(name = "passs")
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                .antMatchers("/user/logout").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
    }
    @Configuration
   public static class CorsConfig implements WebMvcConfigurer{
        @Override
       public void addCorsMappings(CorsRegistry registry) {
           // 设置允许跨域的路径
           registry.addMapping("/**")
                   // 设置允许跨域请求的域名
                   .allowedOrigins("*")
                   // 是否允许cookie
                   .allowCredentials(true)
                   // 设置允许的请求方式
                   .allowedMethods("GET", "POST", "DELETE", "PUT")
                   // 设置允许的header属性
                   .allowedHeaders("*")
                   // 跨域允许时间
                   .maxAge(3600);
       }

   }


}
